﻿namespace Shop.Collect.Helper
{
    internal class CouponCodeHelper
    {
        private static readonly char[] r = new char[] { '8', 'k', '7', 'Y', 'a', 'i', 'm', 'r', 'l', 'E', 'b', 'G', 'M', 'e', 'g', 'p', 'D', 'u', 'N', '0', 'V', 'K', 'W', 'n', 'f', 'R', 'S', 'z', 'H', 'o', 's', 'd', 'h', 'w', 'q', '3', '1', 'X', 'c', 'Z', 'B', 'U', '5', 'y', '9', 'A', 'P', 'x', '2', 'F', 't', 'Q', 'C', 'T', '4', 'L', 'v', 'J', 'j', '6' };
        private static readonly Dictionary<char, int> _codeDic = new Dictionary<char, int>();
        private static readonly int len = r.Length;

        static CouponCodeHelper ()
        {
            for (int i = 0; i < len; i++)
            {
                _codeDic.Add(r[i], i);
            }
        }
        public static string CreateCode (long val)
        {
            char[] buf = new char[12];
            int charPos = 12;
            while (val > 0)
            {
                int ind = (int)( val % len );
                buf[--charPos] = r[ind];
                val /= len;
            }
            buf[--charPos] = r[val % len];
            return new string(buf, charPos, ( 12 - charPos ));
        }

        public static long GetCouponCodeId (string code)
        {
            char[] chars = code.ToCharArray();
            long val = _codeDic[chars[0]];
            for (int i = 1; i < chars.Length; i++)
            {
                val = val * len + _codeDic[chars[i]];
            }
            return val;
        }
    }
}
